import { Injectable } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy, StrategyOptions } from 'passport-jwt';
import { JWT_GUARD_NAME } from './jwt.guard';

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy, JWT_GUARD_NAME) {
  constructor() {
    super({
      // 从前端的 request.headers.Authorization 中获取 'Bearer token'
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      jsonWebTokenOptions: {
        // 设置过期时间
        maxAge: '1m',
      },
      secretOrKey: process.env.JWT_SECRET,
    } as StrategyOptions);
  }

  // payload 是通过前端请求中的 token 解析出来的
  // 而 token 是通过 JwtService.sign 创建的
  // 在本例中是直接返回解析的内容
  async validate(payload: unknown) {
    console.log('jwt stratery validate', payload);
    return payload;
  }
}
